package com.eascs.web.o2o.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.web.o2o.web.form.O2oBPAfterLoanForm;
import com.eascs.web.o2o.web.common.BaseMasterViewController;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.web.o2o.web.common.NotKnowTitleRowWriteHandler;
import com.eascs.web.o2o.web.service.O2oCompensatoryService;
//import com.eascs.admin.o2o.internal.controller.PayMentViewController;
import com.eascs.app.dao.PageResult;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Controller
@RequestMapping("compensatory")
public class O2oCompensatoryController extends BaseMasterViewController {

	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "CompensatoryCollection");
	}

	@Autowired
	O2oCompensatoryService service;
	@Reference
	SysOrgService sysOrgService;
	
	@Value("${web.homeUrl}")
	private String adminUrl;
	

	@RequestMapping("/index")
	public String index(O2oBPAfterLoanForm vo) {
		vo.setPageSize(10);
		String o2ourl = "/compensatory/index";
		String reporto2ourl = "/compensatory/download";
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		

			String billCode = vo.getBillCode() == null ? "" : vo.getBillCode();
			String ltd = vo.getLtd() == null ? "" : vo.getLtd();
			String loanUserName = vo.getLoanUserName() == null ? "" : vo.getLoanUserName();
			String hostProvince = vo.getHostProvince() == null ? "" : vo.getHostProvince();
			String loanDateStart = vo.getLoanDateStart() == null ? null : vo.getLoanDateStart();
			String loanDateEnd = vo.getLoanDateEnd() == null ? null : vo.getLoanDateEnd();
			String bankLoan = vo.getBankLoan() == null ? "" : vo.getBankLoan();
			String payDateStart = vo.getPayDateStart() == null ? null : vo.getPayDateStart();
			String payDateEnd = vo.getPayDateEnd() == null ? null : vo.getPayDateEnd();
			o2ourl = UrlUtil.appendUrl(o2ourl, "billCode", billCode);
			o2ourl = UrlUtil.appendUrl(o2ourl, "ltd", ltd);
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanUserName", loanUserName);
			o2ourl = UrlUtil.appendUrl(o2ourl, "hostProvince", hostProvince);
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanDateStart", loanDateStart);
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanDateEnd", loanDateEnd);
			o2ourl = UrlUtil.appendUrl(o2ourl, "bankLoan", bankLoan);
			o2ourl = UrlUtil.appendUrl(o2ourl, "payDateStart", payDateStart);
			o2ourl = UrlUtil.appendUrl(o2ourl, "payDateEnd", payDateEnd);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "billCode", billCode);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "ltd", ltd);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanUserName", loanUserName);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "hostProvince", hostProvince);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanDateStart", loanDateStart);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanDateEnd", loanDateEnd);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "bankLoan", bankLoan);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "payDateStart", payDateStart);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "payDateEnd", payDateEnd);
			o2ourl = o2ourl + "&o2oIndex=";
		ViewContext.put("o2ourl", o2ourl);
		ViewContext.put("reporto2ourl", reporto2ourl);
		Calendar calendar=Calendar.getInstance();
		int year=  calendar.get(Calendar.YEAR);
		PageResult<Object[]> pageResult = service.getDcHkPage(vo);
		String title[]={ "贷款单号", "省区", "经办平台", "借款人姓名", "放款日期", "到期日", "放款银行","首次贷款发放日","代偿金额","代偿日期" ,year-1+"年全年回款" };
		List<String> list = Arrays.asList(title);
		List<String> titleList = new ArrayList<String>(list);
		int month=calendar.get(Calendar.MONTH)+1;
		for (int i = 1; i <= month; i++) {
			if (i < 10) {
				titleList.add(year + "0" + i + "回款");
			} else {
				titleList.add(year + ""+i + "回款");
			}
		}
		int size = titleList.size();  
		String titles[] = (String[])titleList.toArray(new String[size]);
		//Format[] formats = new Format[] { null, null, null, null, null, null, null, null,new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null };//, new DecimalFormat(",##0.00")
		Button[] titleButtons = new Button[] { ButtonHelper.createOpenButton(null, adminUrl+"/detail?billCode={0}") };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
		o2oPagingInfo.setFirstRenderColumnIndex(0);
		o2oPagingInfo.setTitleButtons(titleButtons);
		//o2oPagingInfo.setFormats(formats);
		ViewContext.put("paginationInfo", o2oPagingInfo);
		ViewContext.put("vo", vo);
		
		return "/badloan/compensatory";
	}
	
	


	
	
	@RequestMapping("/download")
	public void dowanload(O2oBPAfterLoanForm vo,HttpServletResponse httpServletResponse, HttpServletRequest request) {
		vo.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = service.getDcHkPage(vo);
		String path = O2oCompensatoryController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/compensatory.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "代偿数据导出.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			Calendar calendar=Calendar.getInstance();
			int month=calendar.get(Calendar.MONTH)+1;
			int year=  calendar.get(Calendar.YEAR);
			// 包含的列
			int col = 11+month;
			// 需要统计的列
			int[] arr = {  };
		
			List<String> titleList = new ArrayList<String>();
			titleList.add(year-1+"年全年回款");
			
			for (int i = 1; i <= month; i++) {
				if (i < 10) {
					titleList.add(year + "0" + i + "回款");
				} else {
					titleList.add(year +""+ i + "回款");
				}
			}
			
			
				// 开始的表格，行，列
				int sheetIndex = 0;
				int rowIndex = 1;
				int columnIndex = 0;
			
				NotKnowTitleRowWriteHandler notKnowTitleRowWriteHandler = new NotKnowTitleRowWriteHandler(pageResult.getData(), col, arr, titleList,
					sheetIndex, rowIndex, columnIndex);
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oCompensatoryController.class.getResourceAsStream("/excelTemplate/compensatory.xls"), notKnowTitleRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
}
